﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Net;
using LinqtoCRMApplication.CRM;
using LinqtoCRM;
using System.Diagnostics;
using System.Xml.Linq;

namespace LinqtoCRMApplication
{
    class Program
    {
        static void Main(string[] args)
        {
			Stopwatch watch = Stopwatch.StartNew();
			//wrap it in a class that implements IService

            //Stopwatch watch = Stopwatch.StartNew();
            CrmService service = new CrmService();
            //watch.Stop();
            //Console.WriteLine("Init done, ctor time: {0}", watch.ElapsedMilliseconds / 1000);
            //service.Url = "http://192.168.150.2:5555/mscrmservices/2007/crmservice.asmx";
            service.Url = "http://192.168.3.11:5555/mscrmservices/2007/crmservice.asmx";
        	service.Credentials = new NetworkCredential("administrator", "pass@word1", "litwareinc");

			CrmAuthenticationToken token = new CrmAuthenticationToken();
			token.AuthenticationType = 0;
			token.OrganizationName = "MicrosoftCRM";
        	service.CrmAuthenticationTokenValue = token;

            
            ICrmService s = new CrmWebService(service);
            CrmQueryProvider p = new CrmQueryProvider(s);
            p.Log = new XmlIndentingWriter(Console.Out);

            

            //QueryExpression q = new QueryExpression();
            //q.EntityName = EntityName.contact.ToString();
            //ColumnSet cset = new ColumnSet();
            //cset.Attributes = new string[] { "firstname" };
            //q.ColumnSet = cset;
            //RetrieveMultipleRequest r = new RetrieveMultipleRequest();
            //r.Query = q;
            //RetrieveMultipleResponse resp = (RetrieveMultipleResponse)service.Execute(r);

            //foreach (var v in resp.BusinessEntityCollection.BusinessEntities)
            //{
            //    Console.WriteLine(((contact)v).firstname);
            //}

            //string fecthxml = "<fetch mapping=\"logical\"><entity name=\"contact\"><all-attributes /></entity></fetch>";
//            string fecthxml = @"<fetch mapping=""logical"">
//                                  <entity name=""contact"">
//                                    <attribute name=""firstname"" />
//                                  </entity>
//                                </fetch>";
//            string resstring = service.Fetch(fecthxml);
//            XDocument res = XDocument.Parse(resstring);
//            var rows = res.Element("resultset").Elements();
//            foreach (var v in rows)
//            {
//                string firstname = v.Element("firstname").Value;
//                Console.WriteLine(firstname);
//            }


            //var res = from c in p.Linq<contact>()
            //          select c.firstname;
            ////    join c in p.Linq<contact>()
            ////on a.accountid.Value equals c.parentcustomerid.Value
            //foreach (var v in res)
            //{
            //    Console.WriteLine(v);
            //}


            //var res = from a in p.Linq<account>()
            //          join c in p.Linq<contact>()
            //          on a.accountid.Value equals c.parentcustomerid.Value
            //          where c.firstname == "Frank"
            //          select new { a.name, c.fullname};

            //var res = from o in p.Linq<opportunity>()
            //          join oc in p.Linq<opportunitycompetitors>() on o.opportunityid.Value equals oc.opportunityid.Value
            //          join c in p.Linq<competitor>() on oc.competitorid.Value equals c.competitorid.Value
            //          where o.name == "jubii"
            //          select new { oppname = o.name, compname = c.name };

            //var res = from a in p.Linq<account>()
            //          //join o in p.Linq<opportunity>() on a.accountid.Value equals o.customerid.Value
            //          join c in p.Linq<contact>() on a.accountid.Value equals c.parentcustomerid.Value
            //          //where
            //              //o.name.Contains("jub") 
            //            //c.fullname.Contains("frank")
            //          select new { a.name };

            //var fpp = new EntityNameReference();
            //fpp.Value = EntityName.email.ToString();

            //var typcodes = new List<string>() { "4042", "4210", "4207", "4201" }
			//var res = from c in p.Linq<contact>()
			//          where c.firstname.Contains("con")
			//          select new { c.firstname };
			//var res = from i in p.Linq<invoice>()
			//          join a in p.Linq<account>() on i.customerid.Value equals a.accountid.Value
			//          select i;

			var res = from c in p.Linq<contact>()
					  where c.fullname.StartsWith("Zwie")
					  select new contact() { contactid = c.contactid };

			foreach (var con in res)
			{
				con.address1_line1 = "foo";
				service.Update(con);
				Console.WriteLine("updated " + con.contactid.Value);
			}

			//QueryExpression query = new QueryExpression();
            //query.EntityName = EntityName.activitypointer.ToString();

            //ColumnSet cols = new ColumnSet();
            //cols.Attributes = new string[] { "activityid", "activitytypecode", "statecode" };

            //query.ColumnSet = cols;

            //query.Criteria.Conditions.AddCondition("regardingobjectid", ConditionOperator.Equal, opportunityId);

            //query.Criteria
            //.Conditions
            //.AddCondition("activitytypecode",
            //ConditionOperator.In,
            //new string[]
            //    {
            //    EntityName.email.ToString(),
            //    EntityName.phonecall.ToString(),
            //    EntityName.letter.ToString(),
            //    EntityName.appointment.ToString(),
            //    }
            //);

            //BusinessEntityCollection retrieved = myService.RetrieveMultiple(query.Query);

            watch.Stop();
            Console.WriteLine("Query time: {0}", watch.ElapsedMilliseconds / 1000);

            Console.WriteLine("----Done----");
            Console.ReadKey();
        }

        static void WriteLine(string s)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(s);
            Console.ForegroundColor = ConsoleColor.Gray;
        }
    }
}

